<?php

namespace app\controller\admin\info;


use app\BaseController;
use app\common\repositories\info\OrderRepository as repository;
use app\common\repositories\info\SizeRepository;
use think\App;
use think\exception\ValidateException;
use ZipArchive;
class Order extends BaseController
{
    protected $repository;

    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }

    public function create()
    {
        $data = $this->checkParams();
        $order = $this->repository->getWhere(['is_del'=>0,'order_sn'=>input('order_sn')]);
        if($order){
            throw new ValidateException('订单已存在');
        }
        $this->repository->create($data);
        return success('添加成功');
    }


    public function update($id)
    {
        $content = $this->repository->getWhere(['order_id'=>$id,'is_del'=>0]);
        if($content->status != 0){
            throw new ValidateException('当前订单已完成，不可修改');
        }
        if(!$content)
            throw new ValidateException('数据不存在');
        $data = $this->checkParams();
        $content->save($data);
        return success('修改成功');
    }


    public function status($id)
    {
        $status = input('status');
        $order = $this->repository->get($id);
        $adminId = request()->adminId();
        if($adminId != 1 && $order->admin_id != $adminId){
            throw new ValidateException('无权限');
        }

        $arr = ['status'=>$status];
        if($status == 2){
            $arr['complete_time'] = date('Y-m-d H:i:s');
        }
        $order->save($arr);
        return success('修改成功');
    }




    public function checkParams()
    {
        $adminId = request()->adminId();
        $params = $this->request->params(['order_sn','admin_id','desc','count']);

        if($adminId != 1){
            $params['admin_id'] = $adminId;
        }else if($params['admin_id'] == 1){
            throw new ValidateException('店铺有误');
        }

        validate([
            'admin_id|店铺'=>'require|max:250',
            'order_sn|订单号'=>'require|max:250',
            'count|图片数量'=>'require|max:250',
            'desc|备注'=>'max:250',
        ])->check($params);


        return $params;
    }


    public function delete($id)
    {
        $order = $this->repository->get($id);
        $adminId = request()->adminId();
        if($adminId != 1 && $order->admin_id != $adminId){
            throw new ValidateException('无权限');
        }
        if($order){
            $order->save(['is_del'=>1]);
        }
        return success('删除成功');
    }


    public function detail($id)
    {
        $content = $this->repository->get($id);
        if(!$content)
            throw new ValidateException('数据不存在');
        $content->append(['shopName']);
        return success($content);
    }



    public function lst()
    {
        [$page,$limit] = $this->request->page();
        $where = $this->request->params(['status','name','order_sn','admin_id',]);

        $adminId = request()->adminId();
        if($adminId != 1){
            $where['admin_id'] = $adminId;
        }

        return success($this->repository->getList($where,$page,$limit));
    }


    public function sizeCreate()
    {
        $adminId = request()->adminId();
        if($adminId != 1){
            throw new ValidateException('无权限');
        }

        $params = $this->request->params(['width','height','name',['count',0]]);
        $this->validate($params,[
            'name|尺寸名称'=>'require|max:255',
            'width|宽度'=>'require|number',
            'height|高度'=>'require|number',
            'count|照片数量'=>'number'
        ]);

        app()->make(SizeRepository::class)->create($params);
        return success('新增成功');
    }


    public function sizeUpdate($id)
    {
        $adminId = request()->adminId();
        if($adminId != 1){
            throw new ValidateException('无权限');
        }

        $data = app()->make(SizeRepository::class)->get($id);

        $params = $this->request->params(['width','height','name',['count',0]]);
        $this->validate($params,[
            'name|尺寸名称'=>'require|max:255',
            'width|宽度'=>'require|number',
            'height|高度'=>'require|number',
            'count|照片数量'=>'number'
        ]);

        $data->save($params);
        return success('编辑成功');
    }

    public function sizeLst()
    {
        [$page,$limit] = $this->request->page();
        $count = app()->make(SizeRepository::class)->getSearch()->where('delete_time',0)
            ->count();
        $list = app()->make(SizeRepository::class)->getSearch()->where('delete_time',0)->page($page,$limit)
            ->order('size_id desc')->select();

        return success(compact('count','list'));
    }


    public function sizeDelete($id)
    {
        $adminId = request()->adminId();
        if($adminId != 1){
            throw new ValidateException('无权限');
        }

        $data = app()->make(SizeRepository::class)->get($id);
        if($data){
            $data->save(['delete_time'=>time()]);
        }
        return success('删除成功');
    }


    public function downLoad($id)
    {
        try {
            $content = $this->repository->getWhere(['order_id'=>$id,'is_del'=>0]);
            if(!$content){
                throw new ValidateException('订单不存在');
            }

            if($content->status == 0){
                throw new ValidateException('当前订单未上传图片');
            }

            $images = $content->images;

            $filePath = 'zip/'.date('Ymd').'/'.md5($content->order_sn).'/';
            $zipSavePath = $filePath.strtotime($content->update_time).'/';
            $zipName = "{$content->name}-{$content->order_sn}-{$content->size_name}.zip";

            if(is_file(public_path().$zipSavePath.$zipName)){
                return success([
                    'path'=>env('SITE_URL').'/'.$zipSavePath.$zipName
                ]);
            }

            $zip = new ZipArchive();
            if(!is_dir(public_path().$zipSavePath)){
                mkdir(public_path().$zipSavePath,0777,true);
            }

            $zip->open(public_path().$zipSavePath.$zipName,ZipArchive::CREATE);
            foreach ($images as $key=>$image){
                if($content->print_style != '单面打印'){
                    $imgPath1 = public_path().trim(str_replace(env('SITE_URL'),'',$image['z']),'/');
                    $imgPath2 = public_path().trim(str_replace(env('SITE_URL'),'',$image['f']),'/');
                    $zip->addFile($imgPath1,"【组合".($key + 1)."】-正面  ({$image['count']}张)-{$content->order_sn}.".self::getF($imgPath1));
                    $zip->addFile($imgPath1,"【组合".($key + 1)."】-反面  ({$image['count']}张)-{$content->order_sn}.".self::getF($imgPath2));
                }else{
                    $imgPath1 = public_path().trim(str_replace(env('SITE_URL'),'',$image['z']),'/');
                    $zip->addFile($imgPath1,'图片'.($key+1)."  ({$image['count']}张)-{$content->order_sn}".'.'.self::getF($imgPath1));
                }
            }
            $zip->close();
            return success([
                'path'=>env('SITE_URL').'/'.$zipSavePath.$zipName
            ]);
        }catch (\Exception $exception){
           throw new ValidateException($exception->getMessage().'|'.$exception->getLine());
        }
    }


    public static function getF($string)
    {
        $data = explode('.',$string);
        return $data[count($data) - 1];
    }


}